<template>
  <div class="confirm_process">
    <one-title title="编辑工艺-生产技术状态确认" @refreshData="init">
      <div class="mes_btn">
        <el-button @click="returnPage">
          <i class="iconfont icon-btn_return"></i>
          返回列表
        </el-button>
        <el-button type="success" @click="save" v-if="!isEmpty&&!isLoading">
          <i class="iconfont icon-btn_Save"></i>
          保存工艺
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
      <div v-loading="isLoading" v-if="!isEmpty">
        <work-order-process
          @saveDesc="saveDesc"
          :infoData="processInfo">
        </work-order-process>
        <work-stage-edit
          ref="workStageEdit"
          :materialName="processInfo.materialName || ''"
          :entry="'workorder'"
          :workstageData="workstageData"
          @tempSave="init"
          @change="handleChange"
          @saveStage="handleSaveStage">
        </work-stage-edit>
      </div>
    </div>
  </div>
</template>

<script>
import EmptyPage from '@/components/EmptyPage'
import {WorkOrderProcess} from '../../../../components/workOrderProcess'
import {WorkStageEdit} from '../../../../components/workStageEdit'
// store模块名称
let storeModule = 'technicalConfirm'

export default {
  name: 'ConfirmProcess',
  components: {
    EmptyPage,
    WorkOrderProcess,
    WorkStageEdit
  },
  data() {
    return {
      isLoading: false,
      isEmpty: false,
      startWatch: false,
    }
  },
  computed: {
    saveState() {
      return this.$store.state.saveState
    },
    detailData() {
      return this.$store.state[storeModule].processDetail
    },
    // 工艺基本信息
    processInfo() {
      return this.$store.state[storeModule].processDetail.workorderTechProc || {}
    },
    // 工序列表
    stageList() {
      return this.$store.state[storeModule].processDetail.workorderWorkstageList || []
    },
    // 可选工序
    workstageData() {
      return this.$store.state[storeModule].workstageData.list || []
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.startWatch = false
      this.isLoading = true
      Promise.all([this.getDetail(), this.getWorkStageList()])
        .finally(() => {
          this.isLoading = false
        })
    },
    // 获取工艺详情
    getDetail() {
      this.isEmpty = false
      let commitObj = {
        method: 'get',
        url: `a/workorder/workorder/getworkorder/${this.$route.query.id}`,
        module: storeModule,
        state: 'processDetail'
      }
      return this.$store.dispatch('saveData', commitObj)
        .then(value => {
          if (Object.keys(value).length === 0) this.isEmpty = true
          this.$refs.workStageEdit.initStageList(this.stageList)
          this.startWatch = true
        })
        .catch(() => {
          this.isEmpty = true
        })
    },
    // 获取可选工序列表
    getWorkStageList() {
      let commitObj = {
        method: 'post',
        url: 'a/workstagerepository/workstageRepository/list',
        module: storeModule,
        state: 'workstageData',
        data: {
          'pageSize': 10000,
          'pageNo': 1
        }
      }
      return this.$store.dispatch('saveData', commitObj)
    },
    // 保存工艺规程描述
    saveDesc(desc) {
      this.$store.commit('UpdateConfirmProcessDesc', desc)
    },
    // 工序序号补0操作
    handleChange(value) {
      value.map((item, index) => {
        let sort = index + 1
        item.sort = sort < 10 ? ('0' + sort) : sort
      })
      this.$store.commit('SetConfirmProcessStageList', value)
    },
    /**
     * 检查派工规则时否满足数字倒序
     */
    checkAssignRule(list) {
      let assignRuleArr = []
      list.map(value => {
        if (value.assignRule !== undefined) {
          if (value.assignRule.includes('-')) {
            assignRuleArr.push(Number(value.assignRule.split('-')[1]))
          } else {
            assignRuleArr.push(0)
          }
        }
      })
      if (list.length !== assignRuleArr.length) {
        this.$message.error({
          message: '请先填写完成派工规则',
          duration: 1500,
          center: true
        })
        return false
      }
      if (JSON.parse(JSON.stringify(assignRuleArr)).toString() !== assignRuleArr.sort((a, b) => b - a).toString()) {
        this.$message.error({
          message: '派工规则不满足按工艺顺序从大到小条件',
          duration: 1500,
          center: true
        })
        return false
      }
      return true
    },
    handleSaveStage() {
      // 保存工艺不跳转
      this.save(false).then(() => {
        this.$refs.workStageEdit.hasStageChange = false
      })
    },
    // 保存工艺
    save(flag = true) {
      if (this.saveState === true) return
      if (!this.checkAssignRule(this.$refs.workStageEdit.stageList)) return
      let commitObj = {
        method: 'post',
        url: 'a/workordertechproc/workorderTechProc/saveWorkorderTechProc',
        data: this.$store.state[storeModule].processDetail,
        noCommit: true
      }
      this.$store.commit('SetSaveState', true)
      return this.$store.dispatch('saveData', commitObj).then(() => {
        this.saveSuccess(flag)
      }).catch(() => {
        this.$store.commit('SetSaveState', false)
      })
    },
    saveSuccess(flag = true) {
      this.$message.success({
        message: '保存成功',
        duration: 1500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
          if (!flag) {
            this.$store.commit('SetSaveState', false)
            this.init()
            return
          }
          this.$store.dispatch('delCurrentViews', this.$route).then(() => {
            this.$store.commit('SetSaveState', false)
            this.$router.push({
              path: '/technicalConfirm',
              query: {callback: '1'}
            })
          })
        }
      })
    },
    // 返回列表页
    returnPage() {
      this.$router.push('/technicalConfirm')
    },
  },
  watch: {
    detailData: {
      // 当前页面数据变化总是会被监听到，我们只需要在我们想要开始监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    }
  }
}
</script>
